// @ts-nocheck
import request from '@/utils/request';
import copy from 'copy-to-clipboard';
import React from 'react';
import {RouteContext, RouteContextType} from "@ant-design/pro-layout";
import {render as renderAmis, toast, utils} from 'amis';
import { alert, AlertComponent, confirm, ToastComponent } from 'amis-ui';
// 导入自定义组件
import '@/components/Amis/renderer/AJCaptchaRenderer'
import '@/components/Amis/renderer/IFramePlus'

import 'amis/lib/helper.css';
import 'amis/lib/themes/cxd.css';
import 'amis/sdk/iconfont.css';
import {useStore} from "jotai";
import initialStatesAtom from "@/store/initialStatesAtom.tsx";
import {useNavigate,useLocation} from "react-router-dom";
import {message} from "antd";



interface RendererProps {
  schema?: any;
}

const AMISRenderer: React.FC<RendererProps> = (props) => {

  let location = useLocation();
  const navigate = useNavigate();
  // @ts-ignore
  // let amisScoped;
  // @ts-ignore
  let theme = 'cxd';
  // @ts-ignore
  let locale = "zh-CN";

  const schema = props.schema;
  const store = useStore();
  const {currentUser} = store.get(initialStatesAtom)

    return (

        <RouteContext.Consumer>
          {(value: RouteContextType) => {
            const { isMobile, hasHeader, hasSiderMenu, collapsed } = value;
            console.log('---AMISRenderer--isMobile:',isMobile,'hasHeader:', hasHeader, 'hasSiderMenu:',hasSiderMenu,'collapsed:', collapsed)
            return <div>
              <ToastComponent theme={theme} key="toast" position={'top-right'} locale={locale}/>
              <AlertComponent theme={theme} key="alert" locale={locale}/>
              {renderAmis(
                  schema,
                  {
                    // props...
                    locale: locale, // 请参考「多语言」的文档
                    //scopeRef: (ref: any) => (amisScoped = ref), // 功能和前面 SDK 的 amisScoped 一样
                    // 传递权限
                    data: utils.createObject({
                      permissions: currentUser?.permissions,
                      roles: currentUser?.roles,
                    }),
                    context: {
                      access: {
                        can: (permission: string[]) => {
                          console.log('----permission---', permission, currentUser?.permissions)
                          const allPermission = '*:*:*';
                          const permissions: string[] = currentUser?.permissions;
                          if (permission && permission.length > 0) {
                            return permissions.some(permission => {
                              return allPermission === permission || permission.includes(permission)
                            })
                          } else {
                            return false;
                          }
                        }
                      }
                    }
                  },
                  {
                    // 下面三个接口必须实现
                    fetcher: ({
                                url, // 接口地址
                                method, // 请求方法 get、post、put、delete
                                data, // 请求数据
                                responseType,
                                config, // 其他配置
                                headers, // 请求头
                              }: any) => {
                      config = config || {};
                      config.withCredentials = true;
                      responseType && (config.responseType = responseType);

                      if (config.cancelExecutor) {
                        config.cancelToken = new (request as any).CancelToken(config.cancelExecutor);
                      }

                      config.headers = headers || {};
                      const token = localStorage.getItem('token');
                      if (token) {
                        config.headers['Authorization'] = 'Bearer ' + token;
                        //clientid
                        //config.headers['clientid'] = CLIENT_ID
                        // 与浏览器插件通信
                        // window.sendMessageToBrowserExt('erp/token',token).then((res:any) => {
                        //   console.log("=====sendToBackgroundViaRelay success=====", res)
                        // }, (err:any) => {
                        //   console.log("=====sendToBackgroundViaRelay error=====", err)
                        // })
                      }
                      if (method !== 'post' && method !== 'put' && method !== 'patch') {
                        if (data) {
                          config.params = data;
                        }

                        return (request as any)[method](url, config);
                      } else if (data && data instanceof FormData) {
                        config.headers = config.headers || {};
                        config.headers['Content-Type'] = 'multipart/form-data';
                      } else if (
                          data &&
                          typeof data !== 'string' &&
                          !(data instanceof Blob) &&
                          !(data instanceof ArrayBuffer)
                      ) {
                        data = JSON.stringify(data);
                        config.headers = config.headers || {};
                        config.headers['Content-Type'] = 'application/json';
                      }

                      return (request as any)[method](url, data, config);

                    },
                    isCancel: (value: any) => (request as any).isCancel(value),
                    copy: (content) => {
                      copy(content);
                      message.success('内容已复制到粘贴板',3)
                    },
                    theme,

                    // 后面这些接口可以不用实现

                    // 默认是地址跳转
                    jumpTo: (
                        to: string /*目标地址*/,
                        action: any /* action对象*/
                    ) => {
                      // 用来实现页面跳转, actionType:link、url 都会进来。
                      const {target='_blank',blank=true,actionType,windowFeatures=''} = action;
                      console.log('---jumpTo---',to,action)
                      if (action && actionType === 'url') {
                        !blank
                            ? (window.location.href = to)
                            : window.open(to, target,windowFeatures);
                        return;
                      } else if (action && blank) {
                        window.open(to, target,windowFeatures);
                        return;
                      }
                      if (/^https?:\/\//.test(to)||to.startsWith('http')) {
                        window.location.href = to;
                      } else {
                        navigate(to);
                      }
                    },
                    // updateLocation: (
                    //   to: any /*目标地址*/,
                    //   replace: boolean | undefined /*是replace，还是push？*/
                    // ) => {
                    //   console.log('---updateLocation---',to,replace,location)
                    //   navigate(to,replace);
                    // },
                    // 用来判断是否目标地址当前地址 用于菜单选中逻辑
                    // isCurrentUrl: (
                    //   url: string /*url地址*/,
                    // ) => {
                    // },
                    notify: (
                        type: 'success' | 'error' | 'info', msg: string
                    ) => {
                      message[type](msg, 5)
                      // toast[type]
                      //     ? toast[type](msg, {closeButton:true,title:type === 'error' ? '系统错误' : '系统消息'})
                      //     : console.warn('[Notify]', type, msg);
                      console.log('[notify]', type, msg);
                    },
                    alert,
                    confirm,
                    useMobileUI: isMobile,
                    // tracker: (eventTracke) => {}
                  },
              )}
            </div>
          }}
        </RouteContext.Consumer>
  );
};

export default AMISRenderer;
